#include <dicom/storage/local_cache.h>
#include <dicom/storage/encrypt.h>
#include <dicom/session.h>
#include <gwbase/base/util.h>
#include <gwbase/base/test_util.h>
#include <gwbase/base/test_harness.h>
#include <surbasic/surbasic.h>
#include <surbasic/TokenManager.h>

using namespace dicom;

class ExpiredTokenPoolTest {};

std::string GenRandomName(size_t n) {
  Random rand;
  std::string name;
  for (size_t i = 0; i < n; ++i) {
    name.push_back(static_cast<char>(rand.Uniform(26) + 'a'));
  }
  return name;
}

AccessToken GenToken(const std::string& email) {
  AccessToken token;
  token.account = email;
  token.access_token = GenRandomName(30);
  return token;
}

const std::string server = "https://open.surdoc.com";
const std::string user = "surdoctestooJUvF20@cc.cc";
const std::string password = "aA111111";

void DoLogin(AccessToken* token) {
  uint64_t key = SDBasic::Login(server, user, password, *token);
  EXPECT_TRUE(key > 0);
}

TEST(ExpiredTokenPoolTest, SimpleTest) {
  ExpiredTokenPool pool;
  AccessToken token;
  DoLogin(&token);

  EXPECT_TRUE(pool.PendingCount() == 0);

  // make same token expired twice
  pool.HandleExpiration(token);
  EXPECT_TRUE(pool.PendingCount() == 1);
  pool.HandleExpiration(token);
  EXPECT_TRUE(pool.PendingCount() == 2);

  AccessToken token2;
  EXPECT_TRUE(pool.GetNextPending(&token2));
  EXPECT_TRUE(token2.account == token.account);

  // another token
  AccessToken token1 = GenToken("abc@123.com");
  pool.HandleExpiration(token1);
  EXPECT_TRUE(pool.PendingCount() == 2);
}

int main() { RunAllTests(); }
